﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XCore.Logger;
using XCore.Web.Middleware;
using XCore.Helper;
using XCore.Extensions;
using SaaS.Core.Logger;
using SaaS.Model.Enums;
using XCore.Authorization;
using XCore.Dependency;

namespace Web.System.Utils
{
    public class SystemExceptionMiddleware : ExceptionMiddleware
    {
        /// <summary>
        /// 总管理员操作日志
        /// </summary>
        public SystemLogger SystemLogger { get; }
        /// <summary>
        /// 总系统错误日志
        /// </summary>
        public ErrorLogger ErrorLogger { get; }
        public SystemExceptionMiddleware(RequestDelegate next) : base(next)
        {
            SystemLogger = IocCollection.Resolve<SystemLogger>();
            ErrorLogger = IocCollection.Resolve<ErrorLogger>();
        }
        public override async Task Invoke(HttpContext context)
        {
            try
            {
                await base.Invoke(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
            finally
            {
                //结束总耗时
                StopwatchHelper.StopTime();
            }
        }
        protected override Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exception is AuthorizationException || exception is PermissionException)
            {
                SystemLogger.Log(context.GetUserId(), exception.Message, SystemLoggerSource.Permission);
            }
            else if (exception is SystemException)
            {
                SystemException message = exception as SystemException;
                SystemLogger.Log(context.GetUserId(), exception.Message, (SystemLoggerSource)message.Code);
            }
            else
            {
                ErrorLogger.Log(exception);
            }
            return base.HandleExceptionAsync(context, exception);
        }
    }
}
